package com.eascs.web.demo.db;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.site.controller.BaseViewController;
import com.eascs.site.view.ViewContext;
import com.eascs.web.exception.RedirectException;

@Controller
public class DbDemoViewController extends BaseViewController {

	@Inject
	private DbDemoService dbDemoService;

	@RequestMapping(value = "/demo/db/")
	public String index() {
		return "/sample/db/index";
	}

	@RequestMapping(value = "/demo/db/transactional/true")
	public String testTransactionalSuccess() {
		dbDemoService.testTransactional(true);
		throw new RedirectException("/demo/db/list");
	}

	@RequestMapping(value = "/demo/db/transactional/false")
	public String testTransactionalFail() {
		dbDemoService.testTransactional(false);
		throw new RedirectException("/demo/db/list");
	}

	@RequestMapping(value = "/demo/db/clean")
	public String clean() {
		dbDemoService.clean();
		throw new RedirectException("/demo/db/");
	}

	@RequestMapping(value = "/demo/db/init")
	public String init() {
		dbDemoService.init();
		throw new RedirectException("/demo/db/");
	}

	@RequestMapping(value = "/demo/db/list")
	public String list() {
		ViewContext.put("objs", dbDemoService.list());
		return "/sample/db/list";
	}

	@RequestMapping(value = "/demo/db/add")
	public String add(DbDemoForm dbDemoForm) {
		DbDemoEntity dbDemoEntity = new DbDemoEntity();
		dbDemoEntity.setId(dbDemoForm.getId());
		dbDemoEntity.setName(dbDemoForm.getName());
		dbDemoEntity.setAddress(dbDemoForm.getAddress());
		dbDemoService.add(dbDemoEntity);
		throw new RedirectException("/demo/db/list");
	}

	@RequestMapping(value = "/demo/db/findbypage/{index}")
	public String findByPage(@PathVariable("index") int index) {
		SqlPageQuery<DbDemoEntity> sqlPageQuery = new SqlPageQuery<>(DbDemoEntity.class, 2, index, "select * from users_test");
		PageResult<DbDemoEntity> pageResult = dbDemoService.findByPage(sqlPageQuery);
		ViewContext.put("objs", pageResult.getData());
		ViewContext.put("count", pageResult.getDbRowCount());
		return "/sample/db/list";
	}

}
